import time

import av
import subprocess as sb
import socket
from queue import Queue
from threading import Thread


def thread_getFrame(channel: Queue):
    command = [
        'ffmpeg', '-f', 'video4linux2', '-i', '/dev/video0', '-s', '1280x720', '-r', '30', '-b:v', '5000k',
        '-y', '-tune', 'zerolatency', '-sc_threshold', '499',
        '-profile', 'baseline', '-preset', 'ultrafast', '-vcodec', 'h264_omx',
        '-f', 'h264', '-pix_fmt', 'yuv420p', '-'
    ]
    # command = [
    #     'ffmpeg', '-f', 'video4linux2', '-i', '/dev/video0', '-s', '640x480', "-b:v", "5000k",
    #     '-y', '-vcodec', 'libx265',
    #     '-f', 'hevc', '-pix_fmt', 'yuv420p', '-'
    # ]
    proc = sb.Popen(command, stdout=sb.PIPE, bufsize=10 ** 8, stderr=sb.PIPE)

    while True:
        chunk = proc.stdout.read(1024)
        if not chunk:
            channel.put(b'[END]')
            break
        proc.stdout.flush()
        channel.put(chunk)
    proc.terminate()


def thread_sendFrame(channel: Queue):
    client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    client.bind(("10.1.0.4", 5501))
    while True:
        chunk = channel.get()
        if chunk == b'[END]':
            break
        lastTime = time.time()
        client.sendto(chunk, ("10.1.0.6", 5500))
        nowTime = time.time()
        print(f"发送延迟：{round((nowTime - lastTime) * 1000, 2)}MS")
    client.close()


if __name__ == '__main__':
    raw_queue = Queue(5)
    thread1 = Thread(target=thread_getFrame, args=(raw_queue, ))
    thread2 = Thread(target=thread_sendFrame, args=(raw_queue, ))
    thread1.setDaemon(True)
    thread2.setDaemon(True)
    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()
